package com.jianli.smart.core.search;

import java.io.IOException;
import java.nio.file.Paths;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

public class LuceneUtil {
	
	public static void write(String[] texts) throws IOException{
		Directory directory = FSDirectory.open(Paths.get("/Users/lijian/work/testindex"));
		StandardAnalyzer analyzer = new StandardAnalyzer();
		
		 
		IndexWriterConfig config = new IndexWriterConfig(analyzer);
		 
		IndexWriter w = new IndexWriter(directory, config);
		for (String text : texts) {
			
	        Document doc = new Document();
	        doc.add(new Field("fieldname", text, TextField.TYPE_STORED));
	        doc.add(new Field("id", text.length()+"", TextField.TYPE_STORED));
	        w.addDocument(doc);
	    }
		w.close();
	}
	
	public static void query(String name) throws ParseException, IOException{
		Directory directory = FSDirectory.open(Paths.get("/Users/lijian/work/testindex"));
		StandardAnalyzer analyzer = new StandardAnalyzer();
		 //读取索引并查询
	    DirectoryReader ireader = DirectoryReader.open(directory);
	    IndexSearcher isearcher = new IndexSearcher(ireader);
	    //解析一个简单的查询
	    QueryParser parser = new QueryParser("fieldname", analyzer);
	    Query query = parser.parse(name);
	    ScoreDoc[] hits = isearcher.search(query, 1000).scoreDocs;
	    //迭代输出结果
	    for (int i = 0; i < hits.length; i++) {
	        Document hitDoc = isearcher.doc(hits[i].doc);
	        System.out.println(hitDoc.get("fieldname")+":"+hitDoc.get("id"));
	    }
	    ireader.close();
	    directory.close();
	}
	
	public static void main(String[] args) throws Exception {
		String[] texts = new String[]{
		        "Mybatis分页插件 - 示例",
		        "Mybatis 贴吧问答 第一期",
		        "Mybatis 示例之 复杂(complex)属性(property)",
		        "Mybatis极其(最)简(好)单(用)的一个分页插件",
		        "Mybatis 的Log4j日志输出问题 - 以及有关日志的所有问题",
		        "Mybatis 示例之 foreach （下）",
		        "Mybatis 示例之 foreach （上）",
		        "Mybatis 示例之 SelectKey",
		        "Mybatis 示例之 Association (2)",
		        "Mybatis 示例之 Association"
		    };
		write(texts);
		query("foreach");
	}
}
